<?php
/**
 * Created by PhpStorm.
 * User: wzy12
 * Date: 2018/10/19
 * Time: 13:47
 */

namespace app\common\model;


use think\Model;

class FreightTemplate extends Model
{
    public function config(){
        return $this->hasMany('FreightConfig', 'template_id', 'id');
    }

    /**
     * 运费模板列表
     * @throws \think\exception\DbException
     */
    public function resList(){
        $list = $this -> order('id desc') -> paginate(3);

        foreach($list as $k => $v){
            $list[$k]['config'] = $v -> config;
        }

        return $list;
    }

    /**
     * 运费模板单条
     */
    public function resFind($id){
        $result = $this -> find($id);

        $result['config'] = $result -> config;

        return $result;
    }

    public function operation($data){
        $action = false;
        if(isset($data['id'])){
            $action = true;
        }

        $result = $this -> validate(true) -> allowField(true) -> isUpdate($action) -> save($data);
        if(false === $result){
            return echoArr(0, $this -> getError());
        }else{
            $id = $this -> id;
            model('FreightConfig') -> where('template_id', $id) -> delete();

            $temp = [];
            if($data['is_enable_default'] == 0){
                unset($data['default']);
            }else{
                $data['default']['template_id'] = $id;
                $temp[] = $data['default'];
            }
            if(isset($data['first_unit'])){
                foreach($data['first_unit'] as $k => $v){
                    $temp[] = [
                        'template_id' => $id,
                        'region' => $data['region'][$k],
                        'first_unit' => $data['first_unit'][$k],
                        'first_money' => $data['first_money'][$k],
                        'continue_unit' => $data['continue_unit'][$k],
                        'continue_money' => $data['continue_unit'][$k]
                    ];
                }
            }

            model('FreightConfig') -> allowField(true) -> isUpdate(false) -> saveAll($temp);

            return echoArr(1, '操作成功');
        }
    }

    public function del($data){
        $res = model('Goods') -> where('template_id', $data) -> select();

        $result = false;
        if(!$res){
            model('FreightConfig') -> where('template_id', $data) -> delete();

            $result = $this -> destroy($data);
        }else{
            return echoArr(0, '请先去除拥有此模板的商品');
        }

        if(false === $result){
            return echoArr(0, '操作失败');
        }else{
            return echoArr(1, '操作成功');
        }
    }
}